package hsb.ruoyi.admin.web.controller.monitor;

import hsb.ruoyi.common.constant.CacheConstants;
import hsb.ruoyi.common.core.cache.LocalCache;
import hsb.ruoyi.common.core.domain.AjaxResult;
import hsb.ruoyi.system.domain.SysCache;
import io.vertx.core.json.Json;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.*;


/**
 * 缓存监控
 *
 * @author ruoyi
 */
@Produces(MediaType.APPLICATION_JSON)
@Path("/monitor/cache")
public class CacheController {
    //  @Autowired
    // private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private LocalCache localCache;

    private final static Map<String, SysCache> caches = new HashMap<>();

    {
        caches.put(CacheConstants.LOGIN_TOKEN_KEY, new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
        caches.put(CacheConstants.SYS_CONFIG_KEY, new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
        caches.put(CacheConstants.SYS_DICT_KEY, new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
        caches.put(CacheConstants.CAPTCHA_CODE_KEY, new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
        caches.put(CacheConstants.REPEAT_SUBMIT_KEY, new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
        caches.put(CacheConstants.RATE_LIMIT_KEY, new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
        caches.put(CacheConstants.LOGIN_SINGLE_TOKEN_KEY, new SysCache(CacheConstants.LOGIN_SINGLE_TOKEN_KEY, "单一登陆"));
    }

    //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GET
    public AjaxResult getInfo() throws Exception {
        //   Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        //    Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        //     Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
//        result.put("info", info);
//        result.put("dbSize", dbSize);
//
//        List<Map<String, String>> pieList = new ArrayList<>();
//        commandStats.stringPropertyNames().forEach(key -> {
//            Map<String, String> data = new HashMap<>(2);
//            String property = commandStats.getProperty(key);
//            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
//            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
//            pieList.add(data);
//        });
//        result.put("commandStats", pieList);
        return AjaxResult.success(result);
    }

    //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GET @Path("/getNames")
    public AjaxResult cache() {

        Collection<String> allKeys = localCache.keys("*");
        Set<String> keys = new HashSet<>();

        for (String key : allKeys) {
            int sub1 = key.indexOf(":");
            if (sub1 > 0) {
                String keyStartStr = key.substring(0, sub1+1);
                keys.add(keyStartStr);
            }
        }
        List<SysCache> result = new ArrayList<>(keys.size() + caches.size());

        for (String key : keys) {
            SysCache sysCache = caches.get(key);
            if (sysCache == null) {
                sysCache = new SysCache(key,"未知");
            }
            result.add(sysCache);
        }
        return AjaxResult.success(result);
    }

    //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GET @Path("/getKeys/{cacheName}")
    public AjaxResult getCacheKeys(@PathParam("cacheName") String cacheName) {
        // Set<String> cacheKyes = redisTemplate.keys(cacheName + "*");

        Collection<String> cacheKeys = localCache.keys(cacheName + "*");

        return AjaxResult.success(cacheKeys);
    }

    //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GET @Path("/getValue/{cacheName}/{cacheKey}")
    public AjaxResult getCacheValue(@PathParam("cacheName") String cacheName, @PathParam("cacheKey") String cacheKey) {
        //  String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        Object cacheObject = localCache.getCacheObject(cacheKey);



        SysCache sysCache = new SysCache(cacheName, cacheKey,    Json.encode(cacheObject));
        return AjaxResult.success(sysCache);
    }

    //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @DELETE
    @Path("/clearCacheName/{cacheName}")
    public AjaxResult clearCacheName(@PathParam("cacheName") String cacheName) {
        //    Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        //   redisTemplate.delete(cacheKeys);

        Collection<String> cacheKeys = localCache.keys(cacheName + "*");
        localCache.deleteObject(cacheKeys);

        return AjaxResult.success();
    }

    //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @DELETE @Path("/clearCacheKey/{cacheKey}")
    public AjaxResult clearCacheKey(@PathParam("cacheKey") String cacheKey) {
        // redisTemplate.delete(cacheKey);

        localCache.deleteObject(cacheKey);

        return AjaxResult.success();
    }

    //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @DELETE @Path("/clearCacheAll")
    public AjaxResult clearCacheAll() {
        //  Collection<String> cacheKeys = redisTemplate.keys("*");
        // redisTemplate.delete(cacheKeys);
        localCache.clearAll();
        return AjaxResult.success();
    }
}
